import { Controller, Get, Module, Param } from "@nestjs/common";

import { PrismaClient } from "@prisma/client";
import configuration from "src/common/configuration";
import { WebResult } from "src/common/web.result";

@Controller("/article/archive")
export class ArticleArchiveController {
  constructor(private readonly prisma: PrismaClient) {
    this.run();
  }

  @Get("/all")
  async getAllArchiveData() {
    const archives = await this.prisma.article_archive.findMany();
    return WebResult.success(archives);
  }

  @Get("/all/name")
  async getAllArchiveName() {
    const archives = await this.prisma.article_archive.findMany({
      select: {
        name: true,
      },
      orderBy: {
        name: "desc",
      },
      distinct: "name",
    });
    const arr = new Array(archives.length);
    for (let i = 0; i < archives.length; i++) {
      arr[i] = archives[i].name;
    }
    return WebResult.success(arr);
  }

  @Get("/name/:name")
  async getArchiveByName(@Param("name") name: string) {
    const archives = await this.prisma.article_archive.findMany({
      where: {
        name: name,
      },
      orderBy: {
        article_id: "desc",
      },
    });
    return WebResult.success(archives);
  }

  @Get("/search/:name")
  async searchArchiveByName(@Param("name") name: string) {
    const archives = await this.prisma.article_archive.findMany({
      where: {
        name: {
          contains: name,
        },
      },
    });
    return WebResult.success(archives);
  }

  async updateArchiveData() {
    const articleArray = await this.prisma.article.findMany({
      select: {
        id: true,
        date: true,
      },
    });
    for (const article of articleArray) {
      // 只管年份归档
      const [archive] = await this.prisma.article_archive.findMany({
        where: {
          article_id: article.id,
        },
      });
      if (!archive) {
        const year = new Date(article.date).getFullYear().toString();
        await this.prisma.article_archive.create({
          data: {
            name: year,
            article_id: article.id,
          },
        });
      }
    }
  }

  run() {
    try {
      this.updateArchiveData();
    } catch (e) {
      console.error(e);
    }
    const updateInterval =
      configuration.article.archiveUpdateInterval * 1000 * 60; // 按分钟
    setTimeout(this.run, updateInterval);
  }
}

@Module({
  controllers: [ArticleArchiveController],
})
export class ArticleArchiveModule {}
